package com.controller;

import com.pojo.SysUser;
import com.pojo.TSysUser;
import com.service.SysUserService;
import com.service.TSysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@Controller
//@RequestMapping("/login")
public class LoginController {
    @Autowired
    private TSysUserService sysUserService;

    @GetMapping("/login")
    public String login(){
        return "login";
    }

//    登录
    @RequestMapping(value = "/login2",method = RequestMethod.GET)
    @ResponseBody
    public void login(HttpServletResponse response, HttpServletRequest request,HttpSession session, String loginName, String password, String rememberMe ,String randomCode) throws IOException {
        TSysUser result=sysUserService.login(loginName,password);
        PrintWriter out = response.getWriter();
        String randomCodeKey = ((String) session.getAttribute("randomCodeKey")).toUpperCase();
        if (result!=null && randomCodeKey.equals(randomCode.toUpperCase())){
            //判断复选框是否选中
            if ("1".equals(rememberMe)) {
                //创建cookie存取用户名和密码
                Cookie c_loginName=new Cookie("loginName",loginName);
                Cookie c_password=new Cookie("password",password);
                //设置cookie的有效时间
                c_loginName.setMaxAge(60*60*24*7);
                c_password.setMaxAge(60*60*24*7);
                //发送cookie
                response.addCookie(c_loginName);
                response.addCookie(c_password);
            }
            session.setAttribute("loginUser",result.getLoginName());
            session.setAttribute("user",result);
            out.print("success");
        }else if (!randomCode.toLowerCase().equals(request.getSession().getAttribute("captcha"))){
            out.print("yzm");
        }else if (result==null){
            out.print("error");
        }
    }

    @GetMapping("toHome")
    public String home(){
        return "home";
    }
}
